package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.Dto.SetmealDto;
import org.example.comment.R;
import org.example.entity.Setmeal;
import org.example.service.CategoryService;
import org.example.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService  categoryService;

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPageInfo = new Page<>();
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, queryWrapper);
        //拷贝
        BeanUtils.copyProperties(pageInfo, dtoPageInfo, "records");
        List<SetmealDto> list = setmealService.listWithFlavor(pageInfo.getRecords());
        dtoPageInfo.setRecords(list);
        return R.success(dtoPageInfo);
    }

    /**
     * 保存套餐信息
     */
    @PostMapping
    //这里的RequestBody注解，用于接收前端传递的参数，参数名为setmealDto
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("保存成功");
    }


    /**
     * 删除套餐
     */
    @DeleteMapping
    //这里的RequestParam注解，用于接收前端传递的参数，参数名为ids
    public R<String> delete(@RequestParam List< Long> ids) {
        log.info("删除套餐，id为：{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }


    /**
     * 修改套餐状态
     */
    @PostMapping("/status/{status}")
    //这里的PathVariable注解，用于接收前端传递的参数，参数名为status
    public R<String> updateStatus(@PathVariable Integer status, Long[] ids) {
        log.info("修改套餐状态：{}", status);
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("修改成功");
    }

    /**
     * 修改套餐
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithFlavor(id);
        return R.success(setmealDto);
    }
}
